package com.scanner.util;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteCantOpenDatabaseException;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaScannerConnection;
import android.text.TextUtils;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ExcelOperator {
	
	public static void write(Context mContext,String path){
		try {
			Label label = null;
			SQLiteDatabase db = null;
			try {
				db = SQLiteDatabase.openDatabase(mContext.getFilesDir() + "/barcode.db3", null, SQLiteDatabase.OPEN_READONLY);//1
			} catch (SQLiteCantOpenDatabaseException e) {
				return;
			}

			Cursor cursor = db.rawQuery("select * from barcode;", null);
			int columnCount = cursor.getColumnCount();
			WritableSheet sheet1 = null;
			WritableWorkbook book = null;
			if (cursor.moveToNext()) {
				File file = new File(path);
				//创建Excel
				book = Workbook.createWorkbook(file);
				MediaScannerConnection.scanFile(mContext, new String[] { file.getAbsolutePath() }, null, null);//刷新文件。。。妈呀我特么。、、、
				//创建sheet
				sheet1 = book.createSheet("Scan_Result", 0);

			}
			LogUtil.e("数据" + columnCount);
			int i = 0;
			while (cursor.moveToNext()) {
				String name = cursor.getString(1);//获取第二列的值
				if (!TextUtils.isEmpty(name)) {
					label = new Label(0, i, name);
					LogUtil.i("表格数据=" + name);
					i++;
					if (sheet1 != null) {
						sheet1.addCell(label);
					}

				}

			}
			if (book != null) {
				book.write();
				book.close();
			}


		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RowsExceededException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void createFolder(String path){
		String [] fileList = path.split("/");
		
		StringBuilder tempPath = new StringBuilder();
		for(int i=0;i<fileList.length;++i){
			//Log.d("BarcodeScanner", fileList[i]);
			tempPath.append("/"+fileList[i]);
			isExist(tempPath.toString());
		}
	}
	
	private static void isExist(String path){
		File file = new File(path);
		if(!file.exists() && !file.isDirectory()){
			file.mkdir();
		}
	}
	
}
